import argparse
import sys

from .core.engine import build, validate
from .template.ppt_parser import open_template, find_slide_map, find_placeholders
from .tools.generate_template import generate as generate_template


def main(argv=None):
    parser = argparse.ArgumentParser(prog="pptgen")
    sub = parser.add_subparsers(dest="cmd")
    p_build = sub.add_parser("build")
    p_build.add_argument("--md", required=True)
    p_build.add_argument("--tpl")
    p_build.add_argument("--out")
    p_validate = sub.add_parser("validate")
    p_validate.add_argument("--md", required=True)
    p_validate.add_argument("--tpl")
    p_inspect = sub.add_parser("inspect")
    p_inspect.add_argument("--tpl", required=True)
    p_template = sub.add_parser("template")
    p_template.add_argument("--out", default="templates/standard_template.pptx")
    args = parser.parse_args(argv)
    if args.cmd == "build":
        build(args.md, template_override=args.tpl, output_override=args.out)
    elif args.cmd == "validate":
        validate(args.md, template_override=args.tpl)
    elif args.cmd == "inspect":
        prs = open_template(args.tpl)
        for idx, slide in enumerate(prs.slides):
            phs = [k for k, _ in find_placeholders(slide)]
            print(f"index={idx} placeholders={phs}")
        slide_map = find_slide_map(prs)
        for slide_id, idx in slide_map.items():
            print(f"mapped slide_id={slide_id} index={idx}")
    elif args.cmd == "template":
        generate_template(args.out)
    else:
        parser.print_help()


if __name__ == "__main__":
    main()